import { ref } from 'vue'
import { fetchLogin, fetchVerifyCode } from '../axioser'
import { ElLoading, ElMessage } from 'element-plus'
import { createRandomNum, getRouter } from '../utils'
import md5 from 'md5'
import store from '../store'
import router from '../router'

export function useLogin() {
  // 用户名
  const userName = ref('')
  // 用户密码
  const userPass = ref('')
  // 用户验证码
  const verifyCode = ref('')
  // 验证码图片
  const verifyCodeImg = ref('')
  // 输入合法性标志
  const inputStatus = ref({
    userName: false,
    userPass: false,
    verifyCode: false,
    check: () =>
      inputStatus.value.userName &&
      inputStatus.value.userPass &&
      inputStatus.value.verifyCode,
  })
  // 获取验证码
  const getVerifyCode = async (
    identity_code,
    loading_target = '.verify-code'
  ) => {
    const Loading = ElLoading.service({ target: loading_target })
    try {
      const {
        data: {
          data: { img },
        },
      } = await fetchVerifyCode({ identity_code })
      verifyCodeImg.value = img
      Loading.close()
    } catch (error) {
      console.error(error)
    }
  }
  //   登录(Core)
  const onLogin = async identity_code => {
    if (inputStatus.value.check()) {
      try {
        const {
          data: {
            data: { uid, name, privilege_level, token, state, bind_vip },
          },
        } = await fetchLogin({
          username: userName.value,
          password: md5(userPass.value),
          verify_code: verifyCode.value,
          identity_code,
        })
        // 存储token
        localStorage.setItem('token', token)
        // 存储vuex
        store.commit('setCurrentManager', {
          uid,
          name,
          privilege_level,
          state,
          bind_vip,
        })

        ElMessage.success({
          message: `登录成功，用户名：${name} (@${bind_vip._wx || '?'})`,
        })
        // 默认跳转至dashborad
        router.push({
          name: getRouter().params['redirect'] || 'dashboard',
        })
      } catch (error) {
        getVerifyCode(identity_code)
        verifyCode.value = ''
        console.error(error)
      }
    } else ElMessage.error({ message: '表单输入不符合预期~' })
  }
  //   生成身份码
  const generateIdentityCode = () => {
    return (
      Math.floor(new Date().getTime() / 1000).toString() +
      '' +
      createRandomNum(1000, 9999)
    )
  }

  return {
    userName,
    userPass,
    verifyCode,
    getVerifyCode,
    verifyCodeImg,
    inputStatus,
    generateIdentityCode,
    onLogin,
  }
}
